import { deleteConfirm } from '@/components/delete-confirm'
import { ElNotification } from 'element-plus'

export function useTableDelete<T extends R.ModelDeleteAble, A extends R.ApiDeleteAble>(api: A) {
  let selections = [] as T[]
  function onSelectionChange(sel?: T[]) {
    if (sel) {
      selections = sel
    }
    return selections
  }
  function onDelete(row?: T) {
    let ids: string[] = []
    if (row) {
      ids = [row.id]
    } else {
      ids = selections.map(item => item.id)
    }
    if (ids.length > 0) {
      deleteConfirm(async () => {
        await api.deleteRows(ids)
        ElNotification({
          title: '提示',
          message: '删除成功。',
          duration: 2000,
          type: 'success',
        })
      })
    } else {
      ElNotification({
        title: '提示',
        message: '请先选择一条数据进行删除',
        duration: 2000,
        type: 'info',
      })
    }
  }
  return {
    onSelectionChange,
    onDelete,
  }
}
